package es.us.lsi.daw.controllers;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import es.us.lsi.daw.util.Vista;

@Controller
public class ControllerAplicacion extends ControllerGenerico {
	
	@RequestMapping("/login.do")
	public ModelAndView login() {		
		return new ModelAndView(Vista.LOGIN);
	}
	
	@RequestMapping("ctxSecurity.do")
	// Acceder al contexto de Spring Security
	public ModelAndView contextoSpringSecurity(ModelMap mapModelo, HttpSession sesion, Authentication authentication, Principal principal) {
		SecurityContext securityContext = (SecurityContext) sesion.getAttribute("SPRING_SECURITY_CONTEXT");
		if(securityContext != null){
			User usuario = (User) securityContext.getAuthentication().getPrincipal();
		}
		return new ModelAndView(Vista.INICIO_PUBLICO);
	}
	
	@RequestMapping("/inicio.do")
	public String inicioPublico(Principal principal, HttpServletResponse response) {
		if (principal != null && principal.getName() != null) {
			return "forward:"+PRIVADO+"inicio.do";
		} else {
			return "forward:/login.do";
		}
	}

	// TODO(fernando)
	@RequestMapping(PRIVADO+"inicio.do") 
	public ModelAndView inicioPrivado(ModelMap modelo, HttpSession sesion,HttpServletRequest request) {

		return new ModelAndView(Vista.INICIO_PRIVADO, modelo);
	}
		
	@RequestMapping("error.do") 
	public void error() {
		throw new IllegalArgumentException("Prueba de error general.");
	}
	
}
